<template>
  <div class="main-content">
    <!--    <div v-if="!isApp" class="front-notice"><i class="el-icon-bell" style="margin-right: 2px"></i>公告：{{ top }}</div>-->
    <!--头部-->
    <div class="scalable-container" :style="{ transform: `scale(${scale})`, transformOrigin: 'top' }">
      <!-- 页面内容 -->
      <div class="content">

        <div class="front-header">
          <div class="front-header-left" v-if="isApp === false">
<!--            <img src="@/assets/imgs/front-logo.png" alt="">-->
            <div class="title">助教下载站</div>
          </div>
          <div class="front-header-center">
            <div class="front-header-nav" :style="{ top: topStyle }">
              <el-menu :default-active="activeMenuIndex" mode="horizontal" router active-text-color="#2A60C9">
                <el-menu-item index="/front/homeFront" style="display: flex;flex-direction: column;align-items: center">
                  <font-awesome-icon v-if="isApp" icon="home" style="margin-bottom: -15px;font-size: 18px"/>
                  首页
                </el-menu-item>
                <!--                <el-menu-item v-if="!isApp" index="/front/forum">论坛</el-menu-item>-->
                <el-menu-item v-if="!isApp" index="/front/contact">关于我们</el-menu-item>
                <el-menu-item v-if="!isApp" index="/front/feedBack">用户反馈</el-menu-item>
                <el-menu-item v-if="isApp" index="/front/feedBack"
                              style="display: flex;flex-direction: column;align-items: center">
                  <font-awesome-icon icon="envelope" style="margin-bottom: -15px;font-size: 18px"/>
                  反馈
                </el-menu-item>
                <!--                <el-menu-item index="/front/success">反馈成功</el-menu-item>-->
                <!--                <el-menu-item index="/front/person">个人中心</el-menu-item>-->


                <!--                <el-input v-if="!isApp" :class="{'rounded-input': true}" prefix-icon="el-icon-search" v-model="name"-->
                <!--                          placeholder="在这里输入你要找的软件" style="width: 260px;margin-right: 8px;margin-left: 30px;"-->
                <!--                          @keyup.enter.native="search()"-->
                <!--                          clearable></el-input>-->
                <!--                <el-button v-if="!isApp" class="el-button" size="mini" round plain type="primary" @click="search()">-->
                <!--                  搜索-->
                <!--                </el-button>-->

                <MySearch @click="search"></MySearch>

                <!--            <el-button class="el-button" size="mini" type="warning" round plain @click="reset">清空</el-button>-->
                <!--                        <el-menu-item>-->
                <!--                          <router-link to="/">后台系统</router-link>-->
                <!--                        </el-menu-item>-->
              </el-menu>
            </div>
          </div>

          <!--          <el-input v-if="isApp === true" prefix-icon="el-icon-search" v-model="name"-->
          <!--                    placeholder="在这里输入你要找的软件"-->
          <!--                    style="width:460px;" clearable></el-input>-->
          <!--          <el-button size="mini" v-if="isApp === true" @click="search()">搜索</el-button>-->
          <form v-if="isApp" @submit.prevent="formSubmit" action="javascript:return true">
            <el-input style="width:100%;margin-left: 18px" prefix-icon="el-icon-search" v-model="name" type="search"
                      id="search-name"
                      placeholder="在这里输入你要找的软件"
                      @keydown="onSearch($event)" @keyup.enter.native="search()">
              <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
            </el-input>
          </form>

          <el-button @click="drawer = true" v-if="isApp" icon="el-icon-s-operation"
                     style="border: none;font-size: 18px;margin-left: 26px"></el-button>


          <el-drawer
              :visible.sync="drawer"
              :direction="direction"
              :modal="false"
              :before-close="handleClose">
            <span
                style="display: flex;flex-direction: column;font-size: 16px;font-weight: bold;justify-content: flex-start">
              <el-button @click="home" type="text">首页</el-button>
              <el-divider></el-divider>
              <el-button @click="about" type="text">关于我们</el-button>
              <el-divider></el-divider>
            </span>
          </el-drawer>


          <div class="front-header-right">
            <!--        <div v-if="!user.username">-->
            <!--          <el-button @click="$router.push('/register')">注册</el-button>-->
            <!--        </div>-->
            <div v-if="isApp === false">
              <!--                            <el-button type="success" plain icon="el-icon-download"></el-button>-->
              <!--                            <el-button type="info" plain icon="el-icon-message-solid"></el-button>-->

              <div class="manager-header-right" v-if="this.userInfo">

                <el-dropdown placement="bottom">
                  <div v-if="userInfo" class="avatar">
                    <img
                        :src="userInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'">
                    <div>{{ userInfo.username || 'username' }}</div>
                  </div>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="goToPerson">个人信息</el-dropdown-item>
                    <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>

              <el-button v-if="!token" size="mini" circle type="primary" icon="el-icon-user"></el-button>
              <el-button class="login" v-if="!token" type="text" @click="showQRCode">登录/注册
              </el-button>
            </div>
          </div>
        </div>

        <!--主体-->
        <div class="main-body">
          <router-view ref="child" @update:user="updateUser"/>
        </div>

      </div>
    </div>

    <!-- 使用全局组件 -->
    <ContactService v-if="!isApp"></ContactService>

    <!-- 模态框容器 -->
    <div class="qrcode-login" v-if="showQRCodeModal">
      <div style="display: flex;flex-direction: row">
<!--        <img src="@/assets/imgs/front-logo.png" style="height: 30px;width: 30px;border-radius: 30px;margin: 6px 5px"/>-->
        <h2 style="font-weight: bold;font-size: 18px;margin-top: 10px">助教下载站</h2>
      </div>

      <div class="qrcode-modal">
        <!-- 关闭按钮 -->
        <el-button type="text" class="close-btn" @click="closeQRCodeModal" icon="el-icon-close"></el-button>
        <!-- 显示二维码图片 -->
        <img class="qrcode-img" :src="data.QRImageUrl" alt="二维码"/>
      </div>
      <p style="margin: 10px 0;text-align: center">微信扫码，授权登录</p>


      <span style="text-align: center;margin-top: 50px">登录即表示已阅读并同意《
        <el-button @click="toContact()" type="text">用户协议</el-button>》和《
        <el-button @click="toContact()" type="text">隐私政策</el-button>》</span>
    </div>


  </div>

</template>

<script>
import axios from 'axios';

export default {
  name: "FrontLayout",

  data() {
    return {
      top: '',
      isApp: false, // true：代表移动端，false：代表PC端
      name: '',
      scale: 1,  // 初始缩放比例为 1，即原始大小
      activeMenuIndex: '/',   // 用于存储当前激活的菜单项
      erweima: '',
      ticket: '',
      showQRCodeModal: false, // 控制模态框的显示
      refreshInterval: null, // 刷新二维码的定时器
      checkStatusInterval: null, // 检查扫码状态的定时器
      data: '',
      userInfo: JSON.parse(localStorage.getItem('userInfo')),
      token: localStorage.getItem('token'),
      drawer: false,
      direction: 'rtl',
      screenHeight: 0,
      topStyle: '0px', // 初始时，设置为0或你想要的任何默认值
    }
  },
  beforeRouteEnter(to, from, next) {
    // 注意：在beforeRouteEnter守卫中，你不能直接访问组件实例 `this`
    // 因为守卫在导航确认前被调用,此时新组件实例还没被创建
    // 可以通过next函数的回调来访问组件实例
    next(vm => {
      if (to.name === 'HomeClick' || to.name === 'HomeDetail' || to.name === 'Search' || to.name === 'Download') {
        vm.activeMenuIndex = '/front/homeFront';
      } else if (to.name === 'Success') {
        vm.activeMenuIndex = '/front/feedBack';
      } else if (to.name === 'Empty') {
        vm.activeMenuIndex = '/front/homeFront';
      } else {
        vm.activeMenuIndex = to.path;
      }
    });
  },
  // 如果你需要在路由变化时（非首次进入）也更新状态，可以使用beforeRouteUpdate
  beforeRouteUpdate(to, from, next) {
    this.activeMenuIndex = to.name === 'HomeClick' || to.name === 'HomeDetail' || to.name === 'Search' || to.name === 'Download' || to.name === 'Empty' ? '/front/homeFront' : to.path;
    next();
  },
  watch: {
    // 监听路由变化
    // $route(to, from) {
    //   // 当路由跳转到 homeClick 页面时，设置首页为激活状态
    //   if (to.name === 'HomeClick' || to.name === 'HomeDetail' || to.name === 'Search') {
    //     this.activeMenuIndex = '/front/homeFront';
    //   } else {
    //     // 否则，使用当前路由路径作为激活状态
    //     this.activeMenuIndex = to.path;
    //   }
    // },
  },
  created() {
    // 在组件创建时，初始化 activeMenuIndex
    this.activeMenuIndex = this.$route.path;
    /** 先判断平台，pc端 or 移动端*/
    this.whichPlatform()
  },
  mounted() {
    // 监听滚轮事件
    window.addEventListener('wheel', this.handleWheelEvent);

    this.setHeaderNavTop(); // 组件挂载后立即设置
    window.addEventListener('resize', this.setHeaderNavTop); // 监听窗口大小变化
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('wheel', this.handleWheelEvent);

    this.closeQRCodeModal(); // 确保在组件销毁前关闭模态框并清除定时器

    window.removeEventListener('resize', this.setHeaderNavTop); // 组件销毁前移除监听器
  },
  methods: {
    toContact() {
      this.$router.push('/front/contact')
      this.showQRCodeModal = false
    },
    setHeaderNavTop() {
      const topValue = window.innerHeight - 100; // 计算top值
      if (topValue < 0) {
        this.topStyle = '0px'; // 如果小于0，则设置为0
      } else {
        this.topStyle = `${topValue}px`; // 否则，设置为计算后的值
      }
    },
    handleClose(done) {
      this.drawer = false
      done()
    },
    loadUserInfo() {
      const token = this.getToken();
      if (token) {
        this.$request.get('/apis/user/info', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }).then(res => {
          localStorage.setItem("userInfo", JSON.stringify(res))  // 存储用户数据
          window.location.reload()
        })
        // } else if (res.status === 401) { // 检查是否因为token过期而返回401状态码
        //   this.$message.error('Token expired, please log in again.');
        //   this.showQRCode(); // 显示二维码或其他登录方式
      } else {
        this.$message.error('No token found');
        this.showQRCode();
      }
    },
    getToken() {
      return localStorage.getItem('token');
    },
    showQRCode() {
      this.showQRCodeModal = true; // 显示模态框
      this.fetchQRCode(); // 请求二维码数据

      // 设置每60秒刷新二维码的定时器
      this.refreshInterval = setInterval(() => {
        this.fetchQRCode(); // 重新获取二维码
      }, 60000); // 60秒

      // 设置每2秒检查扫码状态的定时器
      this.checkStatusInterval = setInterval(() => {
        if (this.data.ticket) {
          this.checkScanStatus(this.data.ticket);
        }
      }, 2000);
    },
    closeQRCodeModal() {
      this.showQRCodeModal = false; // 关闭模态框
      // 清除所有定时器
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      }
      if (this.checkStatusInterval) {
        clearInterval(this.checkStatusInterval);
        this.checkStatusInterval = null;
      }
    },
    fetchQRCode() {
      this.$request.get('/wx/getQR').then(res => {
        this.data = res.data
        // this.erweima = res.data.QRImageUrl // 更新组件的 erweima 数据
        // this.ticket = res.data.ticket
      })
    },
    checkScanStatus() {
      this.$request.get(`/wx/login/status?ticket=${this.data.ticket}`).then(res => {
        if (res.msg === 'failed') {
          // 扫码失败或未关注
          // this.$message.error('扫码失败或未关注公众号，请重新尝试！');
        } else {
          // 关闭模态框
          this.closeQRCodeModal()
          // 显示登录成功提示
          this.$message.success('登录成功！')
          // this.token = response.data.msg
          // const token = response.data.msg; // 或者可能是 response.data.msg，但通常 msg 是状态信息，不是 token
          // 将 token 存储到 localStorage
          localStorage.setItem("token", (res.msg))
          this.loadUserInfo()
        }
      })
    },
    onSearch(e) {
      if (e.keyCode == 13) {
        this.search();
      }
    },
    formSubmit() {
      return false;
    },
    handleWheelEvent(event) {
      // 检查是否按下了Ctrl键
      if (event.ctrlKey) {
        // 防止页面的默认缩放行为
        // event.preventDefault();

        // 判断滚轮方向
        if (event.deltaY < 0) {
          // 滚轮向上滚动，放大页面
          this.scale = Math.min(this.scale + 0.1, 2);  // 最大放大到2倍
        } else {
          // 滚轮向下滚动，缩小页面
          this.scale = Math.max(this.scale - 0.1, 0.5);  // 最小缩小到0.5倍
        }
      }
    },
    search() {
      this.$router.push({
        name: 'Search',
        // query: {
        //   name: this.name,
        // } // 直接传递
      });
    },
    updateUser() {
      this.userInfo = localStorage.getItem('userInfo') || '{}'   // 重新获取下用户的最新信息
    },
// 退出登录
    logout() {
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      this.$router.push("/front/homeFront");
      this.$message.success('退出登录成功！')
      window.location.reload()
    },
    /** PC端、移动端 判断*/
    whichPlatform() {
      if (window.screen.width < 800) {
        this.isApp = true
      } else {
        this.isApp = false
      }
    },
    goToPerson() {
      this.$router.push('/front/person')
    },
    home() {
      this.$router.push('/front/homeFront')
      this.drawer = false
    },
    about() {
      this.$router.push('/front/contact')
      this.drawer = false
    },
  }

}
</script>

<style scoped>
/*pc端*/
@media screen and (min-width: 800px) {
  .front-header {
    display: flex;
    height: 60px;
    line-height: 60px;
    border-bottom: 1px solid #eee;
    background: white;
    position: sticky;
    z-index: 99;
    top: 0;
  }

  .front-header-left {
    width: 230px;
    display: flex;
    align-items: center;
    padding-left: 10px;
  }

  .front-header-left img, .front-header-dropdown img {
    width: 40px;
    height: 40px;
    border-radius: 50%
  }

  .front-header-left .title {
    flex: 1;
    color: #355476;
    cursor: pointer;
    margin-left: 10px;
    font-size: 20px;
    font-weight: bold;
  }

  .front-header-center {
    flex: 1;
    margin-left: 30px;
  }

  .front-header-right {
    width: 200px;
    padding-right: 10px;
    text-align: right;
  }

  .rounded-input /deep/ .el-input__inner {
    border-radius: 30px;
    background-color: #f2f8fe;
  }

  .scalable-container {
    /* 确保缩放时容器本身不会改变大小 */
    width: 100%;
    height: 100%;
    transform-origin: top left;
  }

  .main-content {
    width: 1200px; /* 设置最大宽度 */
    margin: 0 auto; /* 居中显示 */
  }

  .qrcode-login {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
    z-index: 1000;
    display: flex;
    flex-direction: column;
  }

  .qrcode-modal {
    margin: 60px 10px 0 0;
    text-align: center;
    align-items: center;
  }

  .qrcode-img {
    border: 1px solid #e0e0e0;
    text-align: center;
    width: 200px;
    height: 200px;
    padding: 5px;
  }

  /deep/ .el-icon-user{
    font-size: 20px;
  }

  .login{
    color: black;
    font-size: 13px;
  }

  /deep/ .el-button [class*=el-icon-]+span{
    margin-left: 8px;
  }

  .close-btn {
    position: absolute; /* 绝对定位 */
    top: 10px; /* 距离顶部10px */
    right: 16px; /* 距离右边10px */
    z-index: 1001; /* 确保关闭按钮在模态框内容的上方 */
    border: none;
    font-size: 25px;
    color: black;
  }

  .manager-header-right {
    width: 200px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .manager-header-right .avatar {
    display: flex;
    align-items: center;
    padding-right: 10px;
    color: #ccc;
    cursor: default
  }

  .manager-header-right .avatar img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 5px
  }
}

/*移动端*/
@media screen and (max-width: 700px) {
  .front-header {
    display: flex;
    height: 50px;
    line-height: 60px;
    background: white;
  }

  input[type=search]::-webkit-search-cancel-button {
    -webkit-appearance: none; /*去掉默认的小×*/
  }

  .front-header-nav {
    position: fixed;
    left: 0;
    width: 100%;
    z-index: 1000;
    border-top: 1px solid #eaeaea;
    padding: 10px 0 0 0;
    margin-top: 36px;
  }

  .el-menu.el-menu--horizontal {
    border-bottom: none;
  }

  .front-header-nav .el-menu {
    display: flex;
    justify-content: space-around;
    align-items: center;
  }

  .el-menu--horizontal > .el-menu-item.is-active {
    border-bottom: none;
    height: 30px;
  }

  .el-menu--horizontal > .el-menu-item {
    border-bottom: none;
    height: 30px;
  }

  .el-button--text {
    color: inherit; /* 使用继承的颜色，这样就不会有特定的颜色 */
    background-color: transparent; /* 背景颜色设置为透明 */
    padding: 0; /* 移除内边距 */
    border: none; /* 移除边框 */
    width: 20px;
    margin-left: 9px;
  }
}
</style>